<script setup>
import { ref, watch, nextTick, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { http } from '@/utils/request'
import { userUtils } from '@/utils/userUtils'
import { ElMessage } from 'element-plus'
import {
  Loading, House, List, Van, Wallet, DataAnalysis, Guide,
  Location, TrendCharts, MapLocation, Setting, UserFilled
} from '@element-plus/icons-vue'
import { driverOrderAPI } from '@/api/order'
import { aiAPI } from '@/api/ai'

const router = useRouter()
const user = ref({
  name: '未登录',
  avatar: 'https://i.pravatar.cc/100'
})
function goProfile() {
  router.push('/my')
}
function goOrderCreate() {
  router.push('/order/create')
}
function goOrderList() {
  router.push('/order/list')
}
function goAddress() {
  router.push('/address')
}
function goPreference() {
  router.push('/preference')
}
function goBlacklist() {
  router.push('/blacklist')
}
function goVehicleList() {
  router.push('/vehicle/list')
}
function goBalance() {
  router.push('/finance/balance')
}
// 调度相关导航函数
function goDispatchManagement() {
  router.push('/dispatch/management')
}

// 智能客服相关状态
const showChat = ref(false)
const chatInput = ref('')
const chatHistory = ref([])
const loading = ref(false)
const userId = ref(localStorage.getItem('userid'))
const chatBody = ref(null)

// 知识库统计信息
const knowledgeStats = ref({
  total_documents: 0,
  total_categories: 0,
  es_status: '未知',
  last_update: '-'
})

// 快捷问题列表
const quickQuestions = [
  '如何注册滴滴车主？',
  '实时单和预约单有什么区别？',
  '公司车辆可以加入滴滴吗？',
  '如何更换登录手机号？',
  '跑滴滴如何能接到更多订单？',
  '网约车司机证申请条件是什么？',
  '如何提升服务分？',
  '网约车车险怎么买？',
  '电动车跑滴滴电池怎么保养？',
  '网约车司机如何避免职业病？'
]

// 订单相关数据
const orders = ref([])
const orderLoading = ref(false)

// 统计数据
const dailyStats = ref({
  total_orders_today: 0,
  completed_orders_today: 0,
  daily_income: 0,
  avg_rating: 0
})
const statsLoading = ref(false)

// 定时器相关
let statsTimer = null
const STATS_REFRESH_INTERVAL = 30000 // 30秒刷新一次统计数据

// 监听localStorage变化，实现跨页面数据刷新
function handleStorageChange(e) {
  if (e.key === 'statsNeedRefresh') {
    console.log('检测到支付成功，刷新统计数据')
    fetchDailyStats()
    // 清除标记
    localStorage.removeItem('statsNeedRefresh')
  }
}

// 获取知识库统计信息
async function loadKnowledgeStats() {
  try {
    const response = await aiAPI.getKnowledgeStats()
    console.log('API响应:', response.data)
    
    if (response.data && response.data.data) {
      const stats = response.data.data
      console.log('统计数据:', stats)
      
      // 检查ES状态 - es_available在根级别
      const esAvailable = stats.es_available
      console.log('ES可用状态:', esAvailable)
      
      knowledgeStats.value = {
        total_documents: stats.elasticsearch?.total_documents || 0,
        total_categories: Object.keys(stats.elasticsearch?.categories || {}).length,
        es_status: esAvailable ? '正常' : '异常',
        last_update: stats.elasticsearch?.last_update ? 
          new Date(stats.elasticsearch.last_update).toLocaleDateString() : '-'
      }
      console.log('更新后的统计信息:', knowledgeStats.value)
    }
  } catch (error) {
    console.error('加载知识库统计失败:', error)
  }
}

// 获取订单列表
async function fetchOrders() {
  orderLoading.value = true
  try {
    const userid = localStorage.getItem('userid')
    const res = await driverOrderAPI.getDriverOrders(userid)
    // 获取所有订单，前端筛选待接单的订单
    const allOrders = res.data.data || []
    // 只显示状态为0（待接单）的订单
    orders.value = allOrders.filter(order => order.order_status === 0)
  } catch (error) {
    console.error('获取订单失败:', error)
  } finally {
    orderLoading.value = false
  }
}

// 获取司机今日统计数据
async function fetchDailyStats() {
  statsLoading.value = true
  try {
    const userid = localStorage.getItem('userid')
    const res = await driverOrderAPI.getDriverDailyStats(userid)
    if (res.data.code === 200) {
      dailyStats.value = res.data.data
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
  } finally {
    statsLoading.value = false
  }
}

// 启动统计数据定时刷新
function startStatsTimer() {
  // 清除已存在的定时器
  if (statsTimer) {
    clearInterval(statsTimer)
  }
  // 设置新的定时器
  statsTimer = setInterval(() => {
    fetchDailyStats()
  }, STATS_REFRESH_INTERVAL)
}

// 清除统计数据定时器
function clearStatsTimer() {
  if (statsTimer) {
    clearInterval(statsTimer)
    statsTimer = null
  }
}

// 接单功能
async function acceptOrder(orderId) {
  try {
    const userid = localStorage.getItem('userid')
    await driverOrderAPI.acceptOrder({
      order_id: orderId,
      driver_id: userid
    })
    ElMessage.success('接单成功')
    fetchOrders() // 重新获取订单列表
    fetchDailyStats() // 重新获取统计数据
  } catch (error) {
    ElMessage.error('接单失败')
    console.error('接单失败:', error)
  }
}

// 格式化订单状态
function formatStatus(status) {
  const statusMap = {
    0: '待接单',
    1: '待出发', 
    2: '已上车',
    3: '已到达',
    4: '待支付',
    5: '已支付',
    6: '已取消',
    7: '待评价',
    8: '已评价'
  }
  return statusMap[status] || '--'
}

function goOrderDetail(orderId) {
  router.push(`/order/detail/${orderId}`)
}

// 智能客服功能
async function sendMessage() {
  const trimmedMessage = chatInput.value.trim()
  if (!trimmedMessage) {
    console.log('消息为空，不发送')
    return
  }
  
  const userMsg = { sender: 'user', text: trimmedMessage }
  chatHistory.value.push(userMsg)
  loading.value = true
  
  try {
    const res = await aiAPI.customerService(trimmedMessage)
    console.log('客服API响应:', res.data)
    
    if (res.data && res.data.data && res.data.data.answer) {
      chatHistory.value.push({ sender: 'ai', text: res.data.data.answer })
      
      // 显示相关文档信息
      if (res.data.data.relevant_docs && res.data.data.relevant_docs.length > 0) {
        let docsInfo = '参考文档：\n'
        res.data.data.relevant_docs.forEach((doc, index) => {
          docsInfo += `${index + 1}. ${doc.title} (${doc.category})\n`
        })
        chatHistory.value.push({ sender: 'ai', text: docsInfo })
      }
    } else {
      chatHistory.value.push({ sender: 'ai', text: '抱歉，我暂时无法理解您的问题，请稍后再试。' })
    }
  } catch (e) {
    console.error('发送消息失败:', e)
    chatHistory.value.push({ sender: 'ai', text: '客服暂时无法响应，请稍后再试。' })
  } finally {
    loading.value = false
    chatInput.value = ''
  }
}

// 快捷问题
function askQuickQuestion(question) {
  chatInput.value = question
  sendMessage()
}

function handleEnter(e) {
  if (e.key === 'Enter' && chatInput.value.trim()) {
    sendMessage()
  }
}

async function clearChat() {
  chatHistory.value = []
  try {
    await aiAPI.clearChatHistory(userId.value)
  } catch (e) {}
}

function toggleChat() {
  showChat.value = !showChat.value
  if (showChat.value) {
    loadKnowledgeStats() // 加载知识库统计
  }
}

onMounted(async () => {
  console.log('onMounted 执行');
  // 获取当前登录用户的信息
  try {
    const userData = await userUtils.getCurrentUser()
    if (userData) {
      user.value.name = userData.real_name
      user.value.avatar = userData.avatar || 'https://i.pravatar.cc/100'
      console.log('当前用户信息:', user.value)
    } else {
      user.value.name = '未登录'
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    user.value.name = '未登录'
  }

  fetchOrders() // 获取订单列表
  fetchDailyStats() // 获取统计数据
  startStatsTimer() // 启动定时刷新

  // 监听localStorage变化
  window.addEventListener('storage', handleStorageChange)
  // 等待DOM渲染完成后再初始化地图
  nextTick(() => {
    loadAMapScript(() => {
      console.log('地图脚本加载完成');

      // 检查地图容器是否存在
      const mapContainer = document.getElementById('driver-map');
      if (!mapContainer) {
        console.error('地图容器不存在');
        return;
      }

      console.log('地图容器存在，开始初始化地图');

      // 初始化地图的通用函数
      const initMap = (center = [116.397428, 39.90923], zoom = 12) => {
        try {
          const map = new window.AMap.Map('driver-map', {
            zoom: zoom,
            center: center,
            mapStyle: 'amap://styles/normal',
            showLabel: true,
            showBuildingBlock: true
          });

          // 添加标记
          new window.AMap.Marker({
            position: center,
            map: map,
            title: '当前位置',
            icon: new window.AMap.Icon({
              size: new window.AMap.Size(25, 34),
              image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png'
            })
          });

          console.log('地图初始化成功');
          return map;
        } catch (error) {
          console.error('地图初始化失败:', error);
          return null;
        }
      };

      // 先用默认位置初始化地图，避免等待定位时间过长
      console.log('使用默认位置初始化地图');
      const defaultMap = initMap();

      // 然后尝试获取用户位置并更新地图
      if (navigator.geolocation) {
        console.log('准备调用定位');
        ElMessage.info('正在获取您的位置...');

        navigator.geolocation.getCurrentPosition(
          (position) => {
            console.log('定位成功', position);
            const { latitude, longitude } = position.coords;

            // 定位成功后重新初始化地图到用户位置
            if (defaultMap) {
              defaultMap.setCenter([longitude, latitude]);
              defaultMap.setZoom(15);

              // 添加用户位置标记
              new window.AMap.Marker({
                position: [longitude, latitude],
                map: defaultMap,
                title: '您的位置',
                icon: new window.AMap.Icon({
                  size: new window.AMap.Size(30, 40),
                  image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png'
                })
              });

              ElMessage.success('定位成功');
            }
          },
          (err) => {
            console.log('定位失败', err);
            console.log('错误代码:', err.code, '错误信息:', err.message);

            let errorMsg = '定位失败';
            switch(err.code) {
              case 1:
                errorMsg = '用户拒绝了定位请求';
                break;
              case 2:
                errorMsg = '位置信息不可用';
                break;
              case 3:
                errorMsg = '定位超时，请检查网络连接';
                break;
            }

            ElMessage.warning(errorMsg + '，已显示默认位置');
          },
          {
            enableHighAccuracy: false, // 改为false，提高定位速度
            timeout: 10000, // 10秒超时
            maximumAge: 300000 // 5分钟内的缓存位置可用
          }
        );
      } else {
        console.log('浏览器不支持定位');
        ElMessage.info('浏览器不支持定位，已显示默认位置');
      }
    });
  })
})

// 组件卸载时清理定时器和事件监听器
onUnmounted(() => {
  clearStatsTimer()
  window.removeEventListener('storage', handleStorageChange)
})

watch(chatHistory, async () => {
  await nextTick()
  if (chatBody.value) {
    chatBody.value.scrollTop = chatBody.value.scrollHeight
  }
})

function loadAMapScript(callback) {
  if (window.AMap) {
    callback()
    return
  }
  const script = document.createElement('script')
  script.type = 'text/javascript'
  script.src = 'https://webapi.amap.com/maps?v=2.0&key=b40eef5f6996970d70059f7b038a1222'
  script.onload = callback
  document.head.appendChild(script)
}
</script>

<template>
  <div class="layout-root">
    <!-- 侧边栏 -->
    <aside class="sidebar">
      <div class="logo">
        <span class="logo-title">滴滴</span>
      </div>
      <nav class="menu">
        <el-menu default-active="1" class="el-menu-vertical-demo" router>
          <el-menu-item index="1" @click="router.push('/')">
            <el-icon><House /></el-icon>
            <span>首页</span>
          </el-menu-item>
          <el-menu-item index="2" @click="goOrderList">
            <el-icon><List /></el-icon>
            <span>订单管理</span>
          </el-menu-item>
          <el-menu-item index="3" @click="goVehicleList">
            <el-icon><Van /></el-icon>
            <span>车辆管理</span>
          </el-menu-item>
          <el-menu-item index="4" @click="goBalance">
            <el-icon><Wallet /></el-icon>
            <span>账户余额</span>
          </el-menu-item>

          <!-- AI调度功能 -->
          <el-menu-item index="ai" @click="goDispatchManagement">
            <el-icon><DataAnalysis /></el-icon>
            <span>智能调度</span>
          </el-menu-item>

          <!-- 评价分析功能 -->
          <el-menu-item index="evaluation" @click="router.push('/evaluation/dashboard')">
            <el-icon><TrendCharts /></el-icon>
            <span>评价分析</span>
          </el-menu-item>

          <el-menu-item index="5" @click="goAddress">
            <el-icon><MapLocation /></el-icon>
            <span>地址管理</span>
          </el-menu-item>
          <el-menu-item index="6" @click="goPreference">
            <el-icon><Setting /></el-icon>
            <span>偏好设置</span>
          </el-menu-item>
          <el-menu-item index="7" @click="goBlacklist">
            <el-icon><UserFilled /></el-icon>
            <span>黑名单</span>
          </el-menu-item>
        </el-menu>
      </nav>
    </aside>

    <!-- 主体 -->
    <div class="main-content">
      <!-- 顶部导航栏 -->
      <header class="topbar">
        <div class="topbar-title">首页</div>
        <div class="topbar-user" @click="goProfile">
          <img :src="user.avatar" class="topbar-avatar" />
          <span class="topbar-username" @click.stop="router.push('/my')" style="cursor:pointer;">{{ user.name }}</span>
        </div>
      </header>

      <!-- 内容区 -->
      <div class="dashboard">
        <div class="dashboard-main">
          <div class="stat-cards">
            <div class="stat-card">
              <div class="stat-title">今日接单</div>
              <div class="stat-value" v-loading="statsLoading">{{ dailyStats.total_orders_today }}</div>
              <div class="stat-desc">完成订单 {{ dailyStats.completed_orders_today }} 单</div>
            </div>
            <div class="stat-card">
              <div class="stat-title">日收入</div>
              <div class="stat-value" v-loading="statsLoading">￥{{ dailyStats.daily_income.toFixed(1) }}</div>
              <div class="stat-desc">评分 {{ dailyStats.avg_rating }}</div>
            </div>
          </div>
          <el-button type="warning" class="main-btn" size="large" @click="goOrderCreate">开始拉单</el-button>
          <div class="map-section">
            <div id="driver-map" style="width:100%;height:100%;"></div>
          </div>
        </div>
        <div class="dashboard-side">
          <div class="order-list-container">
            <div class="order-list-header">
              <h3>可接订单</h3>
              <el-button size="small" @click="fetchOrders" :loading="orderLoading">刷新</el-button>
            </div>
            <div class="order-list-content">
              <div v-if="orderLoading" class="order-loading">
                <el-icon class="is-loading"><Loading /></el-icon>
                加载中...
              </div>
              <div v-else-if="orders.length === 0" class="order-empty">
                暂无可接订单
              </div>
              <div v-else class="order-items">
                <div v-for="order in orders" :key="order.id" class="order-item">
                  <div class="order-info">
                    <div class="order-route">
                      <div class="order-start">
                        <span class="order-label">起</span>
                        <span class="order-address">{{ order.start_address }}</span>
                      </div>
                      <div class="order-end">
                        <span class="order-label">终</span>
                        <span class="order-address">{{ order.end_address }}</span>
                      </div>
                    </div>
                    <div class="order-details">
                      <span class="order-amount">￥{{ order.order_amount }}</span>
                      <span class="order-status">{{ formatStatus(order.order_status) }}</span>
                    </div>
                  </div>
                  <div class="order-actions">
                    <el-button 
                      v-if="order.order_status === 0" 
                      type="primary" 
                      size="small" 
                      @click.stop="acceptOrder(order.id)"
                    >
                      接单
                    </el-button>
                    <el-button 
                      v-else 
                      type="info" 
                      size="small" 
                      disabled
                    >
                      已接单
                    </el-button>
                    <el-button 
                      type="text" 
                      size="small" 
                      @click.stop="goOrderDetail(order.id)"
                    >
                      详情
                    </el-button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 智能客服悬浮按钮及对话框 -->
      <div class="chat-float-btn" @click="toggleChat">
        <span class="chat-float-icon">🤖</span>
        <span class="chat-float-text">智能客服</span>
      </div>
      
      <transition name="chat-fade">
        <div v-if="showChat" class="chat-window">
          <div class="chat-header">
            <span>智能客服助手</span>
            <span style="flex:1"></span>
            <span class="chat-clear" @click="clearChat">清空</span>
            <span class="chat-close" @click="toggleChat">×</span>
          </div>
          
          <!-- 知识库统计 -->
          <div class="chat-stats">
            <div class="stat-item">
              <span class="stat-label">文档数:</span>
              <span class="stat-value">{{ knowledgeStats.total_documents }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">分类数:</span>
              <span class="stat-value">{{ knowledgeStats.total_categories }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">ES状态:</span>
              <span class="stat-value" :class="knowledgeStats.es_status === '正常' ? 'status-ok' : 'status-error'">
                {{ knowledgeStats.es_status }}
              </span>
            </div>
          </div>
          
          <!-- 快捷问题 -->
          <div class="quick-questions">
            <div class="quick-title">常见问题:</div>
            <div class="quick-buttons">
              <el-button 
                v-for="question in quickQuestions" 
                :key="question"
                size="small" 
                type="primary" 
                plain
                @click="askQuickQuestion(question)"
                class="quick-btn"
              >
                {{ question }}
              </el-button>
            </div>
          </div>
          
          <div class="chat-body" ref="chatBody">
            <div v-for="(msg, idx) in chatHistory" :key="idx" :class="['chat-msg', msg.sender]">
              <span v-if="msg.sender==='user'" class="chat-avatar user">🧑</span>
              <span v-else class="chat-avatar ai">🤖</span>
              <span class="chat-bubble">{{ msg.text }}</span>
            </div>
            <div v-if="loading" class="chat-msg ai">
              <span class="chat-avatar ai">🤖</span>
              <span class="chat-bubble">正在思考中...</span>
            </div>
          </div>
          
          <div class="chat-footer">
            <input 
              v-model="chatInput" 
              @keydown="handleEnter" 
              :disabled="loading" 
              placeholder="请输入您的问题..." 
              class="chat-input" 
            />
            <button 
              @click="sendMessage" 
              :disabled="loading || !chatInput.trim()" 
              class="chat-send"
            >
              发送
            </button>
          </div>
        </div>
      </transition>
    </div>
  </div>
</template>

<style scoped>
.layout-root {
  display: flex;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
}
.sidebar {
  width: 220px;
  background: #fff;
  box-shadow: 2px 0 8px 0 rgba(34,34,34,0.04);
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 32px;
}
.logo {
  display: flex;
  align-items: center;
  margin-bottom: 32px;
}
.logo-title {
  font-size: 22px;
  font-weight: bold;
  color: #ff8200;
}
.menu {
  width: 100%;
  flex: 1;
}
.sidebar-avatar {
  margin-top: auto;
  margin-bottom: 32px;
  text-align: center;
}
.avatar-img {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  margin-bottom: 8px;
}
.avatar-name {
  font-size: 16px;
  color: #333;
}
.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}
.topbar {
  height: 64px;
  background: linear-gradient(90deg, #2196f3 60%, #42a5f5 100%);
  display: flex;
  align-items: center;
  padding: 0 32px;
  color: #fff;
  font-size: 20px;
  font-weight: bold;
  justify-content: space-between;
}
.topbar-title {
  font-size: 22px;
  font-weight: bold;
}
.topbar-search {
  flex: 1;
  margin: 0 32px;
}
.topbar-user {
  display: flex;
  align-items: center;
  cursor: pointer;
}
.topbar-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  margin-right: 8px;
}
.dashboard {
  display: flex;
  padding: 32px;
  gap: 32px;
  height: calc(100vh - 64px - 64px); /* 减去顶部导航栏和padding的高度 */
  overflow: hidden; /* 防止整个dashboard滚动 */
}

.dashboard-main {
  flex: 2;
  background: #fff;
  border-radius: 18px;
  box-shadow: 0 4px 24px 0 rgba(34,34,34,0.08);
  padding: 32px;
  display: flex;
  flex-direction: column;
  align-items: center;
  overflow: hidden; /* 防止主内容区域滚动 */
}

.dashboard-side {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 18px;
  overflow: hidden; /* 防止侧边栏滚动 */
}
.stat-cards {
  display: flex;
  gap: 32px;
  margin-bottom: 24px;
}
.stat-card {
  background: #f5f7fa;
  border-radius: 12px;
  padding: 18px 32px;
  text-align: center;
  min-width: 120px;
}
.stat-title {
  font-size: 16px;
  color: #888;
}
.stat-value {
  font-size: 32px;
  font-weight: bold;
  color: #2196f3;
  margin: 8px 0;
}
.stat-desc {
  font-size: 14px;
  color: #666;
}
.main-btn {
  margin: 24px 0;
  font-size: 20px;
  width: 240px;
  height: 56px;
  border-radius: 28px;
  background: #ff8200;
  color: #fff;
  font-weight: bold;
  box-shadow: 0 8px 24px 0 rgba(255,130,0,0.12);
}
.map-section {
  width: 100%;
  height: 300px; /* 调整地图高度 */
  background: #e3f2fd;
  border-radius: 12px;
  margin-top: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden; /* 防止地图区域滚动 */
}
.map-placeholder {
  color: #2196f3;
  font-size: 18px;
}
.quick-func-card {
  background: linear-gradient(90deg, #ffe0b2 60%, #ffcc80 100%);
  border-radius: 12px;
  padding: 18px 24px;
  color: #ff8200;
  font-weight: bold;
  margin-bottom: 8px;
  cursor: pointer;
}
.quick-title {
  font-size: 16px;
  margin-bottom: 6px;
}
.quick-desc {
  font-size: 14px;
  color: #b26a00;
  font-weight: normal;
}

/* 订单列表样式 */
.order-list-container {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 24px 0 rgba(34,34,34,0.08);
  padding: 20px;
  height: 600px; /* 固定高度 */
  display: flex;
  flex-direction: column;
  overflow: hidden; /* 防止整个容器滚动 */
}

.order-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
  flex-shrink: 0; /* 防止头部被压缩 */
}

.order-list-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
  font-weight: bold;
}

.order-list-content {
  flex: 1;
  overflow-y: auto; /* 只让内容区域滚动 */
  overflow-x: hidden;
  padding-right: 4px; /* 为滚动条留出空间 */
}

/* 自定义滚动条样式 */
.order-list-content::-webkit-scrollbar {
  width: 6px;
}

.order-list-content::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.order-list-content::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.order-list-content::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.order-loading {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
  color: #666;
  font-size: 14px;
}

.order-empty {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
  color: #999;
  font-size: 14px;
}

.order-items {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.order-item {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
  border: 1px solid #e9ecef;
  transition: all 0.2s;
}

.order-item:hover {
  border-color: #2196f3;
  box-shadow: 0 2px 8px 0 rgba(33,150,243,0.1);
}

.order-info {
  margin-bottom: 12px;
}

.order-route {
  margin-bottom: 8px;
}

.order-start, .order-end {
  display: flex;
  align-items: center;
  margin-bottom: 4px;
}

.order-label {
  background: #2196f3;
  color: #fff;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: bold;
  margin-right: 8px;
  flex-shrink: 0;
}

.order-end .order-label {
  background: #ff8200;
}

.order-address {
  font-size: 14px;
  color: #333;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.order-details {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 8px;
}

.order-amount {
  font-size: 16px;
  font-weight: bold;
  color: #ff8200;
}

.order-status {
  font-size: 12px;
  color: #666;
  padding: 2px 8px;
  background: #f0f0f0;
  border-radius: 4px;
}

.order-actions {
  display: flex;
  justify-content: flex-end;
}
/* 美化整体页面 */
.layout-root {
  font-family: 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
  background: linear-gradient(135deg, #f7f8fa 60%, #e3f2fd 100%);
}
.main-content {
  background: #fafdff;
  border-radius: 18px;
  box-shadow: 0 4px 24px 0 rgba(34,34,34,0.08);
  margin: 16px 0;
}
/* 悬浮客服按钮 */
.chat-float-btn {
  position: fixed;
  right: 36px;
  bottom: 36px;
  z-index: 1000;
  background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
  color: #fff;
  border-radius: 28px;
  box-shadow: 0 4px 16px 0 rgba(102, 126, 234, 0.18);
  padding: 12px 24px;
  display: flex;
  align-items: center;
  cursor: pointer;
  font-size: 18px;
  transition: box-shadow 0.2s;
}
.chat-float-btn:hover {
  box-shadow: 0 8px 32px 0 rgba(102, 126, 234, 0.28);
}
.chat-float-icon {
  font-size: 22px;
  margin-right: 8px;
}
/* 对话窗口 */
.chat-window {
  position: fixed;
  right: 36px;
  bottom: 90px;
  width: 480px;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 8px 32px 0 rgba(102, 126, 234, 0.18);
  z-index: 1100;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  animation: chat-pop 0.3s;
}
@keyframes chat-pop {
  0% { transform: scale(0.8); opacity: 0; }
  100% { transform: scale(1); opacity: 1; }
}
.chat-header {
  background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
  color: #fff;
  padding: 20px 28px;
  font-size: 22px;
  font-weight: bold;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.chat-close {
  cursor: pointer;
  font-size: 28px;
  font-weight: normal;
}

/* 知识库统计 */
.chat-stats {
  background: #f8f9fa;
  padding: 12px 20px;
  display: flex;
  justify-content: space-between;
  border-bottom: 1px solid #e9ecef;
}
.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  font-size: 12px;
}
.stat-label {
  color: #666;
  margin-bottom: 2px;
}
.stat-value {
  font-weight: bold;
  color: #667eea;
}
.status-ok {
  color: #28a745;
}
.status-error {
  color: #dc3545;
}

/* 快捷问题 */
.quick-questions {
  background: #fff;
  padding: 16px 20px;
  border-bottom: 1px solid #e9ecef;
}
.quick-title {
  font-size: 14px;
  color: #333;
  margin-bottom: 8px;
  font-weight: bold;
}
.quick-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}
.quick-btn {
  font-size: 12px;
  padding: 4px 8px;
  height: auto;
  line-height: 1.2;
}

.chat-body {
  flex: 1;
  padding: 24px;
  background: #f7fafd;
  overflow-y: auto;
  max-height: 320px;
}
.chat-msg {
  display: flex;
  align-items: flex-end;
  margin-bottom: 16px;
}
.chat-msg.user {
  flex-direction: row-reverse;
}
.chat-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #e3f2fd;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 26px;
  margin: 0 12px;
}
.chat-avatar.user {
  background: #ffecb3;
}
.chat-avatar.ai {
  background: #bbdefb;
}
.chat-bubble {
  background: #fff;
  border-radius: 16px;
  padding: 14px 22px;
  max-width: 320px;
  box-shadow: 0 2px 8px 0 rgba(33,150,243,0.08);
  font-size: 18px;
  color: #333;
  word-break: break-all;
  white-space: pre-line;
}
.chat-msg.user .chat-bubble {
  background: #e3f2fd;
  color: #1976d2;
}
.chat-footer {
  display: flex;
  align-items: center;
  padding: 18px 24px;
  background: #f7fafd;
  border-top: 1px solid #e3eaf2;
}
.chat-input {
  flex: 1;
  border: none;
  border-radius: 16px;
  padding: 14px 18px;
  font-size: 18px;
  background: #fff;
  margin-right: 16px;
  box-shadow: 0 1px 4px 0 rgba(33,150,243,0.04);
}
.chat-input:focus {
  outline: none;
  box-shadow: 0 2px 8px 0 rgba(33,150,243,0.10);
}
.chat-send {
  background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
  color: #fff;
  border: none;
  border-radius: 16px;
  padding: 14px 28px;
  font-size: 18px;
  font-weight: bold;
  cursor: pointer;
  transition: background 0.2s;
}
.chat-send:disabled {
  background: #b3e5fc;
  cursor: not-allowed;
}
/* 对话窗口动画 */
.chat-fade-enter-active, .chat-fade-leave-active {
  transition: opacity 0.3s;
}
.chat-fade-enter-from, .chat-fade-leave-to {
  opacity: 0;
}
.chat-clear {
  color: #fff;
  background: #ff9800;
  border-radius: 8px;
  padding: 2px 12px;
  margin-right: 12px;
  font-size: 15px;
  cursor: pointer;
  transition: background 0.2s;
}
.chat-clear:hover {
  background: #ffb74d;
}
/* 响应式设计 */
@media (max-width: 1200px) {
  .dashboard {
    padding: 20px;
    gap: 20px;
  }
  
  .order-list-container {
    height: 500px; /* 在小屏幕上减少高度 */
  }
}

@media (max-width: 768px) {
  .dashboard {
    flex-direction: column;
    height: auto;
    overflow: visible;
  }
  
  .dashboard-main {
    margin-bottom: 20px;
  }
  
  .order-list-container {
    height: 400px; /* 在移动端进一步减少高度 */
  }
  
  .map-section {
    height: 200px;
  }
  
  .chat-window {
    width: 90vw;
    right: 5vw;
  }
}
</style>
